package cn.itsource.intercepto;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if (token != null){
            return true;
        }
        //在session中获取登录用户
        Object object = request.getSession().getAttribute("USER_IN_SESSION");
        if (object == null){

            //设置编码格式，否则中文会乱码
            response.setCharacterEncoding("utf-8");
            //将数据输出到前端，只要是false或noLogin，就要跳转到登录页面
            //{"success":false,"message":"toLogin"}
            response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
            return false; //拦截
        }
        return true;  //放行
    }
}
